const mysql = require("mysql2");

const config = require("../config/config");

// 创建连接池
const connectionPool = mysql.createPool({
	host: config.MYSQL_HOST,
	port: config.MYSQL_PORT,
	database: config.MYSQL_DATABASE,
	user: config.MYSQL_USER,
	password: config.MYSQL_PASSWORD,
	connectionLimit: 10
});

// 连接是否成功
connectionPool.getConnection((err, connection) => {
	if (err) {
		console.log("获取连接失败", err);
		return;
	}

	// 获取connection，测试连接
	connection.connect((err) => {
		if (err) {
			console.log("连接数据库失败", err);
		} else {
			console.log("连接数据库成功");
		}
	});
});

// 获取连接池对象并导出
const connection = connectionPool.promise();
module.exports = connection;
